<template>
  <div>
    <el-card class="mb">
      <template #header>
        <div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="showTrademarkDialog({ id: 0, tmName: '', logoUrl: '' })"
            >添加</el-button
          >
        </div>
      </template>
      <el-table border :data="trademarkList">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        />
        <el-table-column label="品牌名称" prop="tmName" />
        <el-table-column label="品牌LOGO">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.logoUrl"
              fit="write"
              class="trademark-img"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="warning"
              icon="el-icon-edit-outline"
              size="small"
              @click="showTrademarkDialog(scope.row)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="delTrademarkList(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[3, 6, 9, 12]"
      :page-size="pageSize"
      layout="prev, pager, next, jumper, ->, total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      :title="`${rulesForm.id ? '修改' : '添加'}品牌`"
      :visible.sync="dialogVisible"
    >
      <el-form
        label-width="100px"
        ref="rulesFormRef"
        :model="rulesForm"
        :rules="rules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="rulesForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌名称" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            list-type="picture"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="rulesForm.logoUrl"
              :src="rulesForm.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>

            <template #tip>
              <div class="el-upload_tip">只能上传jpg文件,且不超过250kb</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqTrademarkList,
  reqUpdateTrademark,
  reqSaveTrademark,
  reqDelTrademark
} from '@/api/product/trademark'

export default {
  name: 'Trademark',

  //组件里直接定义数据
  data() {
    return {
      currentPage: 1,
      pageSize: 3,
      total: 100,
      trademarkList: [],
      dialogVisible: false,
      imageUrl: '',
      BASE_URL: process.env.VUE_APP_BASE_API,
      rulesForm: {
        id: 0,
        tmName: '',
        logoUrl: ''
      },
      rulesFormRef: '',
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        logoUrl: [{ required: true, message: '请上传品牌LOGO' }]
      }
    }
  },

  mounted() {
    this.getTrademarkList()
  },

  methods: {
    // 组件里直接发送请求
    async getTrademarkList() {
      // console.log(this.pageSize, 'pageSize')
      const res = await reqTrademarkList(this.currentPage, this.pageSize)
      // console.log(res)
      this.trademarkList = res.data.records
      this.pageSize = res.data.size
      this.currentPage = res.data.current
      this.total = res.data.total
    },
    handleSizeChange() {
      // console.log(pageSize)
      // this.pageSize = pageSize
      this.getTrademarkList()
    },
    handleCurrentChange(currentPage) {
      // console.log(currentPag)
      this.currentPage = currentPage
      this.getTrademarkList()
    },

    showTrademarkDialog(row) {
      this.dialogVisible = true
      this.rulesForm.id = row.id
      this.rulesForm.tmName = row.tmName
      this.rulesForm.logoUrl = row.logoUrl
    },

    //添加品牌
    async showAddTrademark() {
      const addTrademark = await reqSaveTrademark(this.tmName, this.logoUrl)
      this.dialogVisible = false
      this.$message({
        message: `${this.rulesForm.id ? '修改' : '添加'}品牌${
          addTrademark.message
        }`,
        type: 'success'
      })
      this.handleClose()
      this.getTrademarkList()
    },

    // //修改品牌
    async updateTrademark() {
      const updTrademark = await reqUpdateTrademark(this.rulesForm)
      this.dialogVisible = false
      this.$message({
        message: `${this.rulesForm.id ? '修改' : '添加'}品牌${
          updTrademark.message
        }`,
        type: 'success'
      })
      this.handleClose()
      this.getTrademarkList()
    },

    //整个表单校验

    // 确定提交按钮
    submitForm() {
      this.$refs['rulesFormRef'].validate((valid) => {
        if (!valid) return false
        if (!this.rulesForm.id) {
          this.showAddTrademark()
        }
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.$refs['rulesFormRef'].clearValidate()
      this.rulesForm.tmName = ''
      this.rulesForm.logoUrl = ''
    },

    handleAvatarSuccess(res) {
      //上传成功服务器返回的图片地址
      this.rulesForm.logoUrl = res.data

      this.$refs['rulesFormRef'].clearValidate(['logoUrl'])
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt250k = file.size / 1024 < 250

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt250k) {
        this.$message.error('上传头像图片大小不能超过 250kb!')
      }
      return isJPG && isLt250k
    },

    //删除品牌
    delTrademarkList(row) {
      // console.log('id', id)

      this.$confirm(`此操作将永久删除${row.tmName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await reqDelTrademark(row.id)
        this.$message.success('删除成功!')

        this.getTrademarkList()
      })

      // this.$message.success('删除品牌成功')
      // this.getTrademarkList()
    }
  }
}
</script>

<style lang="less" scoped>
.trademark-img {
  width: 100px;
  height: 80px;
}
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
